﻿using System;
using System.Data;
using System.Drawing;
using System.Web.UI;
using Telerik.Web.UI;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.APP_UI.Common;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Project_Expense : System.Web.UI.Page
    {
        private IProject projectBLL;
        private ComboBLL comboBLL = new ComboBLL();
        private Expense_BLL exp = new Expense_BLL();
        //private IExpenseBLL expCtrl = new ExpenseBLL();
        private IExpenseGroupBLL ExpGrp = new ExpenseGroupBLL();
        private string strType;
        private Main main = new Main();
        private SsMng ssmng = new SsMng();

        protected void Page_Load(object sender, EventArgs e)
        {
            strType = Request.QueryString["type"].ToString();

            if (strType.Length > 0)
            {
                projectBLL = Project_Factory.GetProjectFactory(strType);
            }

            if (!IsPostBack)
            {
                string strProjSeq = Session["ProjectID"].ToString();
                DataTable dtb = projectBLL.GetDataProjectBySequence(strProjSeq);

                if (dtb.Rows.Count > 0)
                {
                    litTitle.Text = dtb.Rows[0]["bgm_prj_name"].ToString();
                    lblRecordStatus.Text = dtb.Rows[0]["record_status"].ToString();
                }

                lblBgmProjSeq.Text = strProjSeq;
                lblBgmSourceSeq.Text = Request.QueryString["source"].ToString();
                LoadRblBgmExpGrpSeq();
                LoadTreeBgmExpense();
                LoadDtgExpense();

                SetButtonVisible(Main.EditMode.View);
            }
        }

        protected void LoadRblBgmExpGrpSeq()
        {
            rblBgmExpGrpSeq.DataSource = ExpGrp.Search(-1);
            rblBgmExpGrpSeq.DataBind();

            rblBgmExpGrpSeq.SelectedIndex = 1;
        }

        protected void LoadDdlResourceSubGroup()
        {
            Nullable<int> nBgmExpSeq = main.ConvertNullInt(lblBgmExpSeq.Text);
            ddlResourceSubGroup.DataSource = comboBLL.ListResourceDDL(nBgmExpSeq);
            ddlResourceSubGroup.DataBind();
        }

        protected void LoadTreeBgmExpense()
        {
            var dataSource = exp.TreeView(rblBgmExpGrpSeq.SelectedValue, lblBgmSourceSeq.Text);
            
            tView.DataSource = dataSource;
            tView.DataBind();
        } 

        protected void LoadDtgExpense()
        {
            dtgExpense.DataSource = projectBLL.ListProjectExpenseGrid(lblBgmProjSeq.Text
                , lblBgmSourceSeq.Text, rblBgmExpGrpSeq.SelectedValue, false);
            dtgExpense.DataBind();

            DataTable dtb = projectBLL.GetDataProjectExpenseGroup(lblBgmProjSeq.Text, lblBgmSourceSeq.Text);
            for (int i = 0; i < dtb.Rows.Count; i++)
            {
                for (int j = 0; j < rblBgmExpGrpSeq.Items.Count; j++)
                {
                    if (dtb.Rows[i]["bgm_exp_grp_seq"].ToString() == rblBgmExpGrpSeq.Items[j].Value)
                    {
                        rblBgmExpGrpSeq.Items[j].Text = dtb.Rows[i]["bgm_exp_grp_name"].ToString() + " : [<span class='span'>" + Convert.ToDouble(dtb.Rows[i]["total_amount"]).ToString("#,###.00") + "</span>]";
                    }
                }
            }
        }

        protected void SetButtonVisible(Main.EditMode EditMode)
        {
            switch (EditMode)
            {
                case Main.EditMode.AddNew :
                    cmdInsert.Visible = true;
                    cmdUpdate.Visible = false;
                    cmdCancel.Visible = false;
                    cmdDelete.Visible = false;

                    PanelEdit.Visible = true;
                    break;
                case Main.EditMode.Edit :
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = true;
                    cmdCancel.Visible = true;
                    cmdDelete.Visible = true;

                    PanelEdit.Visible = true;
                    break;
                case Main.EditMode.View :
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = false;
                    cmdCancel.Visible = false;
                    cmdDelete.Visible = false;

                    PanelEdit.Visible = false;
                    break;
                default :
                    break;
            }

            switch (lblRecordStatus.Text)
            {
                case "A":
                case "P":
                case "C":
                    cmdInsert.Enabled = false;
                    cmdUpdate.Enabled = false;
                    cmdDelete.Enabled = false;
                    break;
                case "W":
                case "U":
                case "R":
                    cmdInsert.Enabled = true;
                    cmdUpdate.Enabled = true;
                    cmdDelete.Enabled = true;
                    break;
                default:
                    break;
            }
        }

        private void SetExpenseData(string strBgmExpSeq)
        {
            DataTable dtb = exp.GetInfo(strBgmExpSeq);

            if (dtb.Rows.Count > 0)
            {
                lblBgmExpSeq.Text = dtb.Rows[0]["bgm_exp_seq"].ToString();
                lblBgmExpName1.Text = dtb.Rows[0]["bgm_exp_name"].ToString();
                lblBgmExpName2.Text = dtb.Rows[0]["bgm_exp_name1"].ToString();
                lblBgmExpName3.Text = dtb.Rows[0]["bgm_exp_name2"].ToString();
                lblBgmExpGrpSeqReal.Text = dtb.Rows[0]["bgm_exp_grp_id_real"].ToString();

                string strBgmExpGrpSeqReal = dtb.Rows[0]["bgm_exp_grp_id_real"].ToString();
                string strIcmResourceSeq = dtb.Rows[0]["icm_resource_seq"].ToString();

                if (strBgmExpGrpSeqReal == "3")
                {
                    PanelInv.Visible = true;
                    LoadDdlResourceSubGroup();
                }
                //else if (!string.IsNullOrEmpty(strIcmResourceSeq))
                //{
                //    PanelInv.Visible = false;
                //    lblResourceGroup.Text = strIcmResourceSeq;
                //}
                else
                {
                    PanelInv.Visible = false;
                }
            }
        }

        private bool CheckData()
        {
            bool bOK = true;
            string strError = "";
            double dAmount;

            if (txtTotalAmount.Text.Length == 0)
            {
                strError = "กรุณากรอกข้อมูล [จำนวนเงิน]";
                bOK = false;
            }
            else if (!double.TryParse(txtTotalAmount.Text, out dAmount))
            {
                strError = "[จำนวนเงิน] เป็นตัวเลขเท่านั้น";
                bOK = false;
            }
            else if (dAmount < 0)
            {
                strError = "[จำนวนเงิน] ต้องมากกว่า 0 เท่านั้น";
                bOK = false;
            }
            else if (PanelInv.Visible)
            {
                if (ddlResourceSubGroup.SelectedValue.Length == 0)
                {
                    strError = "กรุณากรอกข้อมูล [รายการพัสดุ]";
                    bOK = false;
                }
                else if (txtUnitQty.Text.Length == 0)
                {
                    strError = "กรุณากรอกข้อมูล [จำนวนหน่วย]";
                    bOK = false;
                }
                else if (!double.TryParse(txtUnitQty.Text, out dAmount))
                {
                    strError = "[จำนวนหน่วย] เป็นตัวเลขเท่านั้น";
                    bOK = false;
                }
                else if (dAmount < 0)
                {
                    strError = "[จำนวนหน่วย] ต้องมากกว่า 0 เท่านั้น";
                    bOK = false;
                }
                else if (txtUnitPrice.Text.Length == 0)
                {
                    strError = "กรุณากรอกข้อมูล [จำนวนเงินต่อหน่วย]";
                    bOK = false;
                }
                else if (!double.TryParse(txtUnitPrice.Text, out dAmount))
                {
                    strError = "[จำนวนเงินต่อหน่วย] เป็นตัวเลขเท่านั้น";
                    bOK = false;
                }
                else if (dAmount < 0)
                {
                    strError = "[จำนวนเงินต่อหน่วย] ต้องมากกว่า 0 เท่านั้น";
                    bOK = false;
                }
            }

            if (!bOK)
            {
                main.MessageAlert(Page, strError);
            }

            return bOK;
        }

        private void ClearData()
        {
            lblBgmProjExpSeq.Text = "";
            txtDescr.Text = "";
            txtTotalAmount.Text = "";
            txtUnitPrice.Text = "";
            txtUnitQty.Text = "";

            if (ddlResourceSubGroup.Items.Count > 0)
            {
                ddlResourceSubGroup.SelectedIndex = 0;
            }
        }

        protected void cmdSearch_Click(object sender, ImageClickEventArgs e)
        {
            string strSearch = txtSearch.Text;

            foreach (RadTreeNode node in tView.Nodes)
            {
                SearchRecursive(node, strSearch);
            }
        }

        private void SearchRecursive(RadTreeNode _node, string strSearch)
        {
            string strNodeText = _node.Text;

            if (strNodeText.IndexOf(strSearch) > -1)
            {
                _node.BackColor = Color.Yellow;
                _node.ExpandParentNodes();
            }
            else
            {
                _node.BackColor = Color.Transparent;
            }

            foreach (RadTreeNode node in _node.Nodes)
            {
                SearchRecursive(node, strSearch);
            }
        }

        protected void rblBgmExpGrpSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadTreeBgmExpense();
            LoadDtgExpense();
        }

        protected void tView_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            if (e.Node.Nodes.Count == 0)
            {
                string strBgmExpSeq = e.Node.Value;

                SetExpenseData(strBgmExpSeq);

                if (cmdUpdate.Visible)
                {
                    SetButtonVisible(Main.EditMode.Edit);
                }
                else
                {
                    SetButtonVisible(Main.EditMode.AddNew);
                }
            }
            else if (!cmdUpdate.Visible)
            {
                SetButtonVisible(Main.EditMode.View);
            }
        }

        protected void dtgExpense_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "GridEdit")
            {
                GridDataItem item = (GridDataItem)e.Item;
                string strBgmProjExpSeq = main.WebString(item["bgm_proj_exp_seq"].Text);
                DataTable dtb = projectBLL.GetDataProjectExpenseBySequence(strBgmProjExpSeq);

                if (dtb.Rows.Count > 0)
                {
                    SetExpenseData(dtb.Rows[0]["bgm_exp_seq"].ToString());
                }

                lblBgmProjExpSeq.Text = strBgmProjExpSeq;
                txtDescr.Text = dtb.Rows[0]["descr"].ToString();
                txtTotalAmount.Text = dtb.Rows[0]["total_amount"].ToString();

                if (PanelInv.Visible)
                {
                    txtUnitPrice.Text = dtb.Rows[0]["unit_price"].ToString();
                    txtUnitQty.Text = dtb.Rows[0]["unit_qty"].ToString();
                    ddlResourceSubGroup.SelectedValue = dtb.Rows[0]["icm_res_item_seq"].ToString();
                }

                SetButtonVisible(Main.EditMode.Edit);
            }
            else if (e.CommandName == "Filter" || e.CommandName == "Sort" || e.CommandName == "Page")
            {
                LoadDtgExpense();
            }
        }

        protected void cmdInsert_Click(object sender, EventArgs e)
        {
            if (!CheckData())
            {
                return;
            }

            try
            {
                string strBgmProjSeq = lblBgmProjSeq.Text;
                string strBgmSourceSeq = lblBgmSourceSeq.Text;
                string strBgmExpSeq = lblBgmExpSeq.Text;
                string strTotalAmount = txtTotalAmount.Text;
                string strDescr = txtDescr.Text;
                string strEmpSeq = ssmng.EmpSeq;

                Nullable<decimal> dUnitPrice = null;
                Nullable<int> nUnitQty = null;
                Nullable<int> nIcmResItemSeq = null;

                if (PanelInv.Visible)
                {
                    dUnitPrice = Convert.ToDecimal(txtUnitPrice.Text);
                    nUnitQty = main.ConvertNullInt(txtUnitQty.Text);
                    nIcmResItemSeq = main.ConvertNullInt(ddlResourceSubGroup.SelectedValue.Split('-')[0]);
                }

                projectBLL.InsertProjectExpense(strBgmProjSeq, strBgmSourceSeq, strBgmExpSeq, strTotalAmount
                    , strDescr, nIcmResItemSeq, nUnitQty, dUnitPrice, null, null, null, strEmpSeq);

                LoadDtgExpense();
                ClearData();
                SetButtonVisible(Main.EditMode.View);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            if (!CheckData())
            {
                return;
            }

            try
            {
                string strBgmProjExpSeq = lblBgmProjExpSeq.Text;
                string strBgmProjSeq = lblBgmProjSeq.Text;
                string strBgmSourceSeq = lblBgmSourceSeq.Text;
                string strBgmExpSeq = lblBgmExpSeq.Text;
                string strTotalAmount = txtTotalAmount.Text;
                string strDescr = txtDescr.Text;
                string strEmpSeq = ssmng.EmpSeq;

                Nullable<decimal> dUnitPrice = null;
                Nullable<int> nUnitQty = null;
                Nullable<int> nIcmResItemSeq = null;

                if (PanelInv.Visible)
                {
                    dUnitPrice = Convert.ToDecimal(txtUnitPrice.Text);
                    nUnitQty = main.ConvertNullInt(txtUnitQty.Text);
                    nIcmResItemSeq = main.ConvertNullInt(ddlResourceSubGroup.SelectedValue.Split('-')[0]);
                }

                projectBLL.UpdateProjectExpense(strBgmProjExpSeq, strBgmProjSeq, strBgmSourceSeq, strBgmExpSeq, strTotalAmount
                    , strDescr, nIcmResItemSeq, nUnitQty, dUnitPrice, null, null, null, strEmpSeq);

                LoadDtgExpense();
                ClearData();
                SetButtonVisible(Main.EditMode.View);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            string strBgmProjExpSeq = lblBgmProjExpSeq.Text;

            projectBLL.DeleteProjectExpense(strBgmProjExpSeq);

            LoadDtgExpense();
            ClearData();
            SetButtonVisible(Main.EditMode.View);
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            ClearData();
            SetButtonVisible(Main.EditMode.View);
        }

        private void SetTotalAmount()
        {
            double dUnitQty = (double.TryParse(txtUnitQty.Text, out dUnitQty) ? dUnitQty : 0);
            double dUnitPrice = (double.TryParse(txtUnitPrice.Text, out dUnitPrice) ? dUnitPrice : 0);

            txtTotalAmount.Text = (dUnitQty * dUnitPrice).ToString("#,##0.00");
        }

        protected void txtUnitQty_TextChanged(object sender, EventArgs e)
        {
            SetTotalAmount();
        }

        protected void txtUnitPrice_TextChanged(object sender, EventArgs e)
        {
            SetTotalAmount();
        }
    }
}
